package com.woniu.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author LXB
 * @Date 2023/8/19 19:47
 * @Description
 **/
public class TokenFluxUtil {
    /**
     * 获取token
     */
    public static String getToken(org.springframework.http.server.reactive.ServerHttpRequest request, String key) {
        String token = request.getHeaders().getFirst(key);
        if (token == null) {
            token = request.getQueryParams().getFirst(key);
        }
        if (token == null || token.length() == 0) {
            return null;
        }
        return token;
    }

    /**
     * 获取token
     */
    public static String getToken(org.springframework.http.server.ServerHttpRequest request, String key) {
        String token = request.getHeaders().getFirst(key);
        if (token == null) {
            token = urlRequest(request.getURI().toString()).get(key);
        }
        if (token == null || token.length() == 0) {
            return null;
        }
        return token;
    }

    private static Map<String, String> urlRequest(String URL) {
        if (URL.indexOf("?") == -1) {
            return new HashMap<>();
        }
        Map<String, String> mapRequest = new HashMap<>();
        String[] split = URL.split("\\?");
        String strUrlParam = split[1];
        // 每个键值为一组
        String[] params = strUrlParam.split("[&]");
        for (String param : params) {
            String[] arrSplitEqual = param.split("[=]");
            // 解析出键值
            if (arrSplitEqual.length > 1)
                // 正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            else {
                if (arrSplitEqual[0] != "")
                    // 只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
            }
        }
        return mapRequest;
    }


}
